package cn.hpclub.server.controller.admin;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.ApiDescribe;
import cn.hpclub.server.model.CmccOrder;
import cn.hpclub.server.model.StatisticTransaction;
import cn.hpclub.server.service.TransactionLogService;
import cn.hpclub.server.service.product.ProductService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.ExcelRenderUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TransactionLogController extends BaseAdminController<StatisticTransaction>{


    /**
     *
     * @Title: list
     * @Description:分页获取首页弹窗数据列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("opt_time")){
            searchInfo.put("opt_time", DateKit.getLastDay());
        }
        if(searchInfo.containsKey("api")){
            if("-1".equals(searchInfo.get("api"))){
                searchInfo.remove("api");
            }

        }
        initSelectApi();
        setAttrs(searchInfo);
        findByPageForSearch("SELECT *  ",
                            TransactionLogService.service.getSqlExceptSelect(searchInfo));
        render("/admin/transaction_log_list.tpl");
    }


    public void initSelectApi(){
        List<Record> list = Db.find("select api from api_describe");
        setAttr("api_options", list);
    }
    public void exportAll(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("opt_time")){
            searchInfo.put("opt_time", DateKit.getLastDay());
        }
        if(searchInfo.containsKey("api")){
            if("-1".equals(searchInfo.get("api"))){
                searchInfo.remove("api");
            }
        }
        SXSSFWorkbook workbook = new TransactionLogService().service.getExcel(searchInfo);
        render(new ExcelRenderUtil(workbook, "调用接口统计"));
    }

    public void exportOneApi(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("opt_time")){
            searchInfo.put("opt_time", DateKit.getLastDay());
        }
        if(searchInfo.containsKey("api")) {
            if ("-1".equals(searchInfo.get("api"))) {
                searchInfo.remove("api");
            }
        }
            SXSSFWorkbook workbook = TransactionLogService.service.getOneApiExcel(searchInfo);
        render(new ExcelRenderUtil(workbook, "失败明细"));
    }



    public void apiDescribeOperateList(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        Page<Record> pager =Db.paginate(getParaToInt(PAGE_NUMBER, 1), getParaToInt(PAGE_SIZE, 10),
                                                           "SELECT *  ", TransactionLogService.service.getApiDescribeSqlExceptSelect(searchInfo));
        setAttr(PAGER, pager);
        render("/admin/transaction_api_describe_list.tpl");
    }




    public void apiDescribeAdd(){
        render("/admin/api_describe_input.tpl");
    }

    public void apiDescribeEdit(){
        String id = getPara("id", null);
        if(StrKit.notBlank(id)){
            ApiDescribe apiDescribe = ApiDescribe.dao.findById(id);
            setAttr("apiDescribe", apiDescribe);
        }
        render("/admin/api_describe_input.tpl");
    }



    /**
     *
     * @Title: save
     * @Description:保存一条首页弹窗数据
     */
    public void saveApiDescribes(){
        ApiDescribe obj = new ApiDescribe();
        String apiDescribeId = getPara("apiDescribeId", null);
        String api = getPara("api", null);
        String describes = getPara("describes", null);

        // 检查必填字段
        if(StrKit.isBlank(api)  || StrKit.isBlank(describes)){
            throw new IllegalArgumentException("参数错误");
        }

        obj.set(ApiDescribe.API, api);
        obj.set(ApiDescribe.DESCRIBES, describes);

        if(StrKit.notBlank(apiDescribeId)){
            // 更新商品信息
            obj.set(ApiDescribe.ID, apiDescribeId);
            obj.update();
        } else{
            if(obj.save()){
                apiDescribeId = String.valueOf(obj.getInt(ApiDescribe.ID));
            }
        }
        redirect("/transactionLog/apiDescribeOperateList");
    }




    public void deleteApiDescribe(){
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }
        boolean deleted = true;
        for(String id : ids){
            ApiDescribe apiDescribe = new ApiDescribe();
            apiDescribe.set(ApiDescribe.ID, id);
            if(!apiDescribe.delete()){
                deleted = false;
                break;
            }
        }
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("code", 1000);
        if(deleted){
            jsonMap.put("message", "success");
        } else{
            jsonMap.put("message", "failed");
        }
        renderJson(jsonMap);
    }


    public void validityApiDescribesUnique(){
        JSONObject jo = null;
        String api = getPara("api", "");
        int apiDescribeId = getParaToInt("apiDescribeId",0);
        boolean flag = TransactionLogService.service.getTariffByCityAndCode(api,apiDescribeId);
        if(!flag){
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "接口名称可用", null);
        }else{
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "接口名称已存在", null);
        }
        renderJson(jo.toString());
    }



}
